<?php
class Engine_Controller extends Zend_Controller_Action
{
	/**
	 * @var Zend_Controller_Action_Helper_FlashMessenger
	 */
	protected $_flashMessenger;

	/**
	 * @var array
	 */
	protected $_messages = array();

	public function init()
	{
		//var_dump($this->_request);
		
		$this->initApplication();
		$this->initView();
	}

	public function initApplication()
	{}

	public function initView()
	{
		$this->view = parent::initView();

		$this->initLayout();

		return $this->view;
	}

	public function initLayout()
	{
		$controller = $this->_request->getControllerName();

		if (file_exists(MODULE_PATH . '/layouts/' . $controller . '.phtml')) {
			$this->_helper->layout->setLayout($controller);
		}
	}

	/**
	 * @param default_core_Services $model
	 * @return Engine_Core_Wrapper
	 */
	protected function getEntryByIdOrAlias($model)
	{
		if (!$id = $this->_request->getParam('id')) {
			if (!$alias = $this->_request->getParam('alias')) {
				$entry = $model->getFirstEntry();
			} else {
				$entry = $model->getEntryByAlias($alias);
			}
		} else {
			$entry = $model->getEntryById($id);
		}

		return $entry;
	}

	/**
	 * @param string $message
	 * @param string $type error
	 * @return void
	 */
	protected function addMessage($message, $type = 'error')
	{
		$this->getMessenger()->addMessage($message);
	}

	/**
	 * @param string $message
	 * @param string $type error
	 * @return void
	 */
	protected function addInstantMessage($message, $type = 'error')
	{
		$this->_messages[] = $message;
	}

	public function postDispatch()
	{
		$this->view->messages = array_merge($this->_messages, $this->getMessenger()->getMessages());
	}

	protected function getMessenger() {
		if (empty($this->_flashMessenger)) {
			$this->_flashMessenger = $this->_helper->getHelper('FlashMessenger');
		}

		return $this->_flashMessenger;
	}

}